import json
import re

import pdfplumber

import common

__TAG = "MccExTbl"
__FIELDS = ["Tbl", "Code"]
__SERVER = common.ServerRemoteRelease

def try_read_page(page):
    page_width = page.width
    left_bbox = (0, 0, page_width / 2, page.height - 64)
    right_bbox = (page_width / 2, 0, page_width, page.height - 64)
    re_text = page.crop(left_bbox).extract_text()
    re_text += "\n"
    re_text += page.crop(right_bbox).extract_text()
    re_text += "\n"
    return re_text


def pdf_to_text():
    txt = ""
    with pdfplumber.open("/home/zhujianfeng/文档/drgs_2_2.pdf") as pdf:
        # page = pdf.pages[1205]
        for page in pdf.pages:
            print(page.page_number)
            if page.page_number < 1508:
                continue
            txt += try_read_page(page)
    with open('out/MccExTbl.txt', 'w', encoding='utf-8') as file:
        file.write(txt)


def extract_code():
    table_pattern = re.compile(r'^表\d+-\d+-\d+')
    icd_10_code_pattern = re.compile(r'^[A-Z]\d+(\.\d+)(x\d+)*(\+\S+\*)*')
    with open('out/MccExTbl.txt', 'r', encoding='utf-8') as file:
        records = []
        for line in file:
            match = re.search(table_pattern, line.strip())
            if match:
                table_name = match.group()  # 使用group()方法提取匹配结果
            match2 = re.search(icd_10_code_pattern, line.strip())
            if match2:
                icd_code = match2.group()  # 使用group()方法提取匹配结果
                # print(icd_code)
                records.append({
                    __FIELDS[0]: table_name,
                    __FIELDS[1]: icd_code
                })
            if len(records) > 0 and len(records) % 100 == 0:
                msg = json.dumps({
                    "fields": __FIELDS,
                    "records": records
                }, ensure_ascii=False)
                print(msg)
                common.batch_add(__TAG, msg, __SERVER)
                records.clear()
        if len(records) > 0:
            msg = json.dumps({
                "fields": __FIELDS,
                "records": records
            }, ensure_ascii=False)
            print(msg)
            common.batch_add(__TAG, msg, __SERVER)

def format_code():
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        data = {
            "fields": __FIELDS,
            "pageIndex": page_index,
            "lastIndex": last_index,
            "pageSize": 200,
            "filters": [
                {"cmd": 12, "args": ["Code", "+"]}
            ]
        }
        data = json.dumps(data, ensure_ascii=False)
        response_data = common.page(__TAG, data, server=__SERVER)
        arm = json.loads(response_data)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        actions = []
        for record in arm['data']['data']:
            rec_id = record['_id']
            code = record['Code'].replace('\n', '').replace('+', '†')
            # print(code)
            action = {
                'action': 23,
                'tag': 'Code',
                '_id': int(rec_id),
                'fv': code
            }
            actions.append(action)
        if len(actions) > 0:
            edit_message = {'actions': actions}
            edit_message = json.dumps(edit_message, ensure_ascii=False)
            print(edit_message)
            common.batch_modify(__TAG, edit_message, server=__SERVER)
        page_index += 1

def export_map():
    arm = common.export_grouped_fv(__TAG, __FIELDS[0], __FIELDS[1], print_res=False, server=__SERVER)
    arm = json.loads(arm)
    # print(arm)
    tbl_dict = arm['data']
    # print(tbl_dict)
    return tbl_dict

if __name__ == '__main__':
    # pdf_to_text()
    # extract_code()
    # format_code()
    export_map()
